# coding=utf-8
"""
base handler
Author: kaspar
Date: 2022-04-01
"""

from handler.handler_base import BaseHandler
from handler import handler_spider
from util.mongo import HandlerMongoDb
from util.my_redis import HandlerRedis
from util.config import Config
from util.logger import Logger

my_mongo = HandlerMongoDb()
my_redis = HandlerRedis()

IP_LIMIT = int(Config.get_conf('server', 'ip_limit'))
spider_website = Config.get_conf('db_mongo', 'db_collection')

class hello(BaseHandler):
    def get(self):
        self.response()

class handlerDealOne(BaseHandler):
    """
    get one website
    """
    def post(self):
        forbidden = False
        request_ip = self.request.headers['X-Real-Ip']
        Logger.writelog('info', 'request ip: {}'.format(request_ip))
        if my_redis.exist(request_ip):
            cnt = int(my_redis.get(request_ip))
            if cnt >= IP_LIMIT:
                self._result['status'] = 1
                remain_time = my_redis.ttl(request_ip)
                h = int(remain_time / 3600)
                r = remain_time - h * 3600
                m = int(r / 60)
                s = (r - m * 60)
                self._result['msg'] = '限制访问,请{}h {}m {}s后再来~'.format(h, m, s)
                forbidden = True
            else:
                my_redis.set(request_ip, cnt + 1)
        else:
            my_redis.set(request_ip, 1)

        if not forbidden:
            res = my_mongo.random_find_one(spider_website)
            reply = {
                'url': res['url'],
                'desp': res['desp']
            }
            self._result['items'] = reply
            self._result['status'] = 0

        self.response()

    def put(self):
        """
        add web manually
        """
        try:
            self.check_param()
            body = self._post_params

            code = body['code']
            url = str(body['url']).strip()
            assert url.startswith('http'), 'url format error, add http:// or https://'
            if code != int(Config.get_conf('authentication', 'token')):
                self._result['items'] = 'code err'
                self._result['status'] = 1
            else:
                res, page = handler_spider.WebCollector.check_url(url)
                if res:
                    my_mongo.insert_one(spider_website, handler_spider.WebCollector.new_web_item(url, page))
                    self._result['status'] = 0
                    self._result['msg'] = 'success'
                else:
                    self._result['msg'] = page
        except Exception as e:
            Logger.writelog('error', e)
            self._result['msg'] = str(e)
        self.response()
